<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>H5图片上传</title>
</head>
<body>
	<input accept="image/*" name="fileInput" class="fileInput" onchange="fileChange(this);"  type="file" value=""/>
	<img id="img" width="300px" height="300px" alt="" src=""/>
</body>
<script type="text/javascript">
	function fileChange(obj){
		if(!obj.files.length)return;
		var file = obj.files[0];
		//FileReader可以将File对象转化成base64，这样可以优先展示图片，然后处理上传操作
		var reader = new FileReader();
		reader.onload = function(){
			var result = this.result;
			if(result.length > 200){
				//进行压缩
				compress(result,file.name);
			}else{
				appendImg(result,file.name);
			}
		};
		reader.readAsDataURL(file);
	}
	
	//图片压缩
	function compress(result,name){
		var img = new Image();
		img.src = result;
		img.onload = function(){
			var initSize = img.src.length;
	        var width = img.width;
	        var height = img.height;
	      //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
	        var ratio;
	        if ((ratio = width * height / 1000000)>1) {
	            ratio = Math.sqrt(ratio);
	            width /= ratio;
	            height /= ratio;
	        }else {
	            ratio = 1;
	        }
	        var canvas = document.createElement("canvas");
	        canvas.width = width;
	        canvas.height = height;
	        var ctx = canvas.getContext("2d");
			// 铺底色
	        ctx.fillStyle = "#fff";
	        ctx.fillRect(0, 0, width, height);
	        ctx.drawImage(img, 0, 0, width, height);
	      	//进行最小压缩
	     	var  ndata = canvas.toDataURL("image/jpeg", 0.1);
	        console.log("压缩前：" + initSize);
	        console.log("压缩后：" + ndata.length);
	        console.log("压缩率：" + ~~(100 * (initSize - ndata.length) / initSize) + "%");
	       canvas.width = canvas.height = 0;
	       appendImg(ndata,name);
		}
        
	}
	//图片显示
	function appendImg(data,name){
		var img = document.getElementById("img");
		img.src = data;
		img.alt = name;
	}
	//图片上传
	function uploadImg(file){
		var fd = new FormData();
		 fd.append('filename', file);
		$.ajax({
		     url: 'xxxx/yyyy',
		     data: fd,
		     type: 'POST',
		     cache: false,
		     processData: false,
		     contentType: false,
		     dataType: 'json',
		     success: function(data) {
		    	 
		     },
		     error: function() {
		    	 
		     }
		});
	}
</script>
</html>